package com.zh.client.user.service;

import com.zh.client.user.dao.UserDao;
import com.zh.pojo.Orderitem;
import com.zh.pojo.Orders;
import com.zh.pojo.User;
import com.zh.utils.MailUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserDao userDao;
    @Override
    public int addUser(User user, HttpServletRequest request) {
        int row = 0;
        String emailMsg = "请<a href='http://localhost:8080/"+request.getContextPath()+"/client/user/activeUser?activeCode="+ user.getActiveCode() + "'>点击</a>激活邮件!";
        try {
            MailUtils.sendMail(user.getEmail(),emailMsg);
            row = userDao.addUser(user);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return row;
    }

    @Override
    public int activeUser(String activeCode) {
        return userDao.activeUser(activeCode);
    }

    @Override
    public int findmail(String email) {
        return userDao.findmail(email);
    }

    @Override
    public int findusername(String username) {
        return userDao.findusername(username);
    }

    @Override
    public User findUserByLogin(User user) {
        return userDao.findUserByLogin(user);
    }

    @Override
    public int modifyUser(User user) {
        return userDao.modifyUser(user);
    }

    @Override
    public List<Orders> findOrderByUser(Integer id) {
        return userDao.findOrderByUser(id);
    }

    @Override
    public List<Orderitem> findOrderitemById(String id) {
        return userDao.findOrderitemById(id);
    }

    @Override
    public void removeOrderById(String id, String flag) {
        if(flag == null){
            List<Orderitem> items = userDao.findOrderitemById(id);
            for (Orderitem item : items) {
                userDao.updatepnum(item);
            }
        }
        //删除订单和订单项
        userDao.deleteOrderById(id);
        userDao.deleteOrderItemById(id);
    }
}
